package me.leiusual.sharing.repository.datasource

import androidx.paging.PageKeyedDataSource
import io.reactivex.observers.DisposableSingleObserver
import me.leiusual.sharing.api.ApiOauth2
import me.leiusual.sharing.api.ApiSharing
import me.leiusual.sharing.api.model.storeproductquery.Product
import me.leiusual.sharing.api.model.storeproductquery.StoreProductQuery
import timber.log.Timber

/**
 * author: leiusual
 * create on: 2019-07-26
 * description:
 */
class ProductDataSource(
    private val apiSharing: ApiSharing,
    private val storeId: Long,
    private val storeAreaId: Long,
    private val categoryId: Long
) : PageKeyedDataSource<Long, Product>() {

  override fun loadInitial(params: LoadInitialParams<Long>, callback: LoadInitialCallback<Long, Product>) {
    val request = StoreProductQuery.Request(
        if (categoryId == 0L) null else categoryId,
        ApiOauth2.CLIENT_ID,
        0,
        params.requestedLoadSize,
        null,
        if (storeAreaId == 0L) null else storeAreaId,
        storeId
    )
    apiSharing.storeProductQuery(request)
        .subscribe(object : DisposableSingleObserver<StoreProductQuery.Response>() {

          override fun onError(e: Throwable) {
            Timber.w(e)
          }

          override fun onSuccess(it: StoreProductQuery.Response) {
            callback.onResult(it.productList, null, 1)
          }
        })
  }

  override fun loadBefore(params: LoadParams<Long>, callback: LoadCallback<Long, Product>) {
    // ignore
  }

  override fun loadAfter(params: LoadParams<Long>, callback: LoadCallback<Long, Product>) {
    val request = StoreProductQuery.Request(
        if (categoryId == 0L) null else categoryId,
        ApiOauth2.CLIENT_ID,
        params.key,
        params.requestedLoadSize,
        null,
        if (storeAreaId == 0L) null else storeAreaId,
        storeId
    )
    apiSharing.storeProductQuery(request)
        .subscribe(object : DisposableSingleObserver<StoreProductQuery.Response>() {

          override fun onError(e: Throwable) {
            Timber.w(e)
          }

          override fun onSuccess(it: StoreProductQuery.Response) {
            val list = it.productList
            callback.onResult(list, if (list.size == params.requestedLoadSize) params.key + 1 else null)
          }
        })
  }
}